package com.zany.util.quartz;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.zany.system.vo.ParameterSingleVO;
import com.zany.util.date.DateFormater;
import com.zany.util.param.SysParamKey;
import com.zany.util.quartz.service.JobService;
import com.zany.util.quartz.vo.AccountCheckVO;

public class AccountCheckJob extends org.springframework.scheduling.quartz.QuartzJobBean {
	
	private static Log logger = LogFactory.getLog(AccountCheckJob.class);
	private JobService jobService;

	public AccountCheckJob() {
	}
	 
	public void setSession(Map arg0) {
		// TODO Auto-generated method stub

	}

	public void setJobService(JobService jobService) {
		this.jobService = jobService;
	}

	@Override
	protected void executeInternal(JobExecutionContext arg0)throws JobExecutionException {
		if(logger.isInfoEnabled()){logger.info("AccountCheckJob.executeInternal()");}
		ParameterSingleVO parameterSingleVO = new ParameterSingleVO();
		List<AccountCheckVO> accountCheckList = new ArrayList<AccountCheckVO>();
		parameterSingleVO.setParamCode(SysParamKey.DATE_ACCOUNT.getKey());
		String path = jobService.getParameterSingleDetail(parameterSingleVO).getParamVal();
		File checkFile = new File(path + "children" + DateFormater.getSystemBeforeNDayDateSimple(1)+".txt");
		if(checkFile.exists()){
			try{
				BufferedReader input = new BufferedReader(new FileReader(checkFile));
				String buffer = input.readLine();
				int dataInt = 1;
				while(buffer!=null){
					AccountCheckVO accountCheckVO = new AccountCheckVO();
					String[] bufferStr = buffer.split("\\|");
					if(bufferStr[0].isEmpty()||bufferStr[1].isEmpty()||bufferStr[2].isEmpty()||
					   bufferStr[3].isEmpty()||bufferStr[4].isEmpty()){
						String returnMsg = "第"+dataInt+"条数据错误！";
						logger.info(returnMsg);
						return ;
					}
					dataInt++;
					accountCheckVO.setHouseId(bufferStr[0]);
					accountCheckVO.setCostMoney(Double.valueOf(bufferStr[1]));
					accountCheckVO.setBankSerial(bufferStr[2]);
					accountCheckVO.setCostDate(bufferStr[3]);
					accountCheckVO.setCostType(bufferStr[4]);
					if(!bufferStr[3].equals(DateFormater.getSystemBeforeNDayDateSimple(1))){
						String returnMsg = "第"+dataInt+"条数据错误,非本日数据！";
						logger.info(returnMsg);
					}else{
						accountCheckList.add(accountCheckVO);
					}
					buffer = input.readLine();
				}
				jobService.insertAccountCheck(accountCheckList);
				jobService.checkBankAccount(accountCheckList);
			}catch (Exception e) {
				String returnMsg = "批量格式错误，请确认！";
				logger.info(returnMsg+e.getMessage());
				return ;
			} 
		}else{
			logger.info("对账文件：" + "children" +DateFormater.getSystemBeforeNDayDateSimple(1)+".txt不存在！");
		}
		
	}
}
